<template>
  <div class="data-main">
    <el-row>
      <el-col
        v-for="attribute in deviceAttributes"
        :key="attribute.token"
        :span="8"
      >
        <div class="data-echarts">
          <diV>
            <span class="data-token">{{ attribute.name }}</span>
            <span class="data-value">{{ attribute.dataValue }}</span>
          </diV>
          <div :id="attribute.token" class="chart" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { formatTime2 } from "@/views/common/js/utils.js";
import { formatDate } from "@/filter/index";
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import {
  echartOptionInit,
  echartOptionLine
} from "@/views/common/js/device/echartsUtils.js";
import { getDeviceTypeAttributes } from "@/api/deviceType";
export default {
  props: {
    deviceToken: {
      type: String
    },
    deviceTypeToken: {
      type: String
    },
    pageNum: {
      type: Number
    },
    pageSize: {
      type: Number
    }
  },
  data() {
    return {
      initmqtt: "",
      client: "",
      tenantTopic: "",
      lineChart: {},
      option: {},
      xData: {},
      yData: {},
      lend: "",
      deviceAttributes: [],
      attributeSelectTokens: []
    };
  },
  mounted() {
    console.log('getCookie("tenant") :>> ', this.$store.getters.tenant.token);
  },
  created() {},
  destroyed() {
    // 页面关闭,关闭mqtt连接
    if (this.client) {
      this.client.end();
    }
  },
  methods: {
    // 页面数据初始化
    init() {
      this.pageNum = 1;
      this.getDeviceRunTimeData();
      if (this.client == "") {
        this.receiveData();
      }
    },
    // 执行参数过滤
    handleParamsFilter() {
      this.pageNum = 1;
      this.xData = [];
      this.yData = [];
      this.lineChart = {};
      this.getDeviceRunTimeData();
    },
    // 获取点位列表
    getDeviceRunTimeData() {
      var params = {
        page: this.pageNum,
        pageSize: this.pageSize,
        attributeTokenList: this.attributeSelectTokens
      };
      getDeviceTypeAttributes(params, this.deviceTypeToken).then(res => {
        const r = res.data;
        // 必须先添加value属性,否则后面不会实时响应变化
        this.deviceAttributes = [];
        r.results.forEach(v => {
          v.dataValue = "";
          this.deviceAttributes.push(v);
        });
        this.$emit("setPageToatl", r.numResults);
        // 初始化echarts实例
        this.$nextTick(() => {
          this.deviceAttributes.forEach(v => {
            this.xData[v.token] = [];
            this.yData[v.token] = [];
            this.lineChart[v.token] = {};
            this.drawLine(v.token);
          });
        });
      });
    },
    // mqtt接收数据
    receiveData() {
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + "/mqtt"
      };

      this.tenantToken = this.$store.state.user.tenant.token;
      this.tenantTopic = `$avic/superlink/iot/${this.tenantToken}/${this.deviceToken}/measurement`;
      this.initmqtt = new initMqtt(param);
      this.client = this.initmqtt.connect(() => {
        console.log("mqtt连接成功,开始订阅主题1");
        this.client.subscribe(this.tenantTopic);
      });

      this.onMessageArrived();
    },
    // 接收数据
    onMessageArrived() {
      this.client.on("message", (topic, message) => {
        var obj = JSON.parse(message.toString());
        if (obj.type == "DeviceMeasurement") {
          if (obj.deviceToken == this.deviceToken) {
            var metadata = obj.request.metadata;
            for (var index in metadata) {
              if (this.xData[index]) {
                this.xData[index].push(
                  formatDate(obj.request.eventDate, "HH:mm:ss", true)
                );
                this.yData[index].push(metadata[index]);
                this.drawLineData(index);
                if (this.yData[index].length > 1800) {
                  this.xData[index].splice(0, 1);
                  this.yData[index].splice(0, 1);
                }
              }

              // 点位列表中实时数据
              this.deviceAttributes.forEach(v => {
                if (v.token == index) {
                  v.dataValue = metadata[index];
                }
              });
            }
          }
        }
      });
    },

    // 折线图初始化
    drawLine(token) {
      // 基于准备好的dom，初始化echarts实例
      var lineChart = this.$echarts.init(document.getElementById(token));
      var option = echartOptionInit(20, 50);
      // 绘制图表
      lineChart.setOption(option);
      // 随浏览器变化响应大小
      window.onresize = function() {
        lineChart.resize();
      };
      this.lineChart[token] = lineChart;
    },

    // 添加数据
    drawLineData(token) {
      var option = echartOptionLine(this.xData[token], this.yData[token]);
      // 绘制图表
      this.lineChart[token].setOption(option);
      this.lineChart[token].resize();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.data-main {
  /* margin: 0 16px 80px 16px; */
}
.data-echarts {
  margin: 20px 5px 0 5px;
}
.chart {
  height: 130px;
}
.data-token {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  line-height: 22px;
  color: #333333;
  margin-left: 13px;
}
.data-value {
  float: right;
  margin-right: 18px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  line-height: 22px;
  color: #2680d2;
}
</style>
